package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeGatewayFilterFactory extends AbstractGatewayFilterFactory {

    @Override
    public GatewayFilter apply(Object config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //1.获取请求与响应对象
                ServerHttpRequest request = exchange.getRequest();
                ServerHttpResponse response = exchange.getResponse();
                //2.判断当前请求是否是登录操作 , 登录操作则放行
                if (request.getURI().getPath().contains("/login")){
                    return chain.filter(exchange);
                }
                //3.从请求头中获取token
                String token = request.getHeaders().getFirst("token");

                if (!AppJwtUtil.verifyToken(token) || "0".equals(AppJwtUtil.getClaimsBody(token).get("id").toString())){
                    //4.解析token失败或者解析token的载荷中的id为0(未登录/是游客登录) , 响应错误信息
                    response.setStatusCode(HttpStatus.UNAUTHORIZED); //401未验证
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    return response.writeWith(Flux.just(response.bufferFactory().wrap("请登录!".getBytes())));
                }
                //5.解析token成功 , 添加请求头 , 将用户id传递到下游微服务
                request.getHeaders().set("id" , AppJwtUtil.getClaimsBody(token).get("id").toString() );
                return chain.filter(exchange);
            }
        };
    }
}
